

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Han Qiu">
  <meta name="keywords" content="">
  
    <meta name="description" content="0、什么是高阶函数高阶函数英文叫Higher-order function。JavaScript的函数其实都指向某个变量。既然变量可以指向函数，函数的参数能接收变量，那么一个函数就可以接收另一个函数作为参数，这种函数就称之为高阶函数。 1、filter函数的使用（过滤数组） MDN：filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。   filter中的回调函数有一">
<meta property="og:type" content="article">
<meta property="og:title" content="js数组中的高阶函数">
<meta property="og:url" content="http://example.com/2022/01/06/js%E6%95%B0%E7%BB%84%E4%B8%AD%E7%9A%84%E9%AB%98%E9%98%B6%E5%87%BD%E6%95%B0/index.html">
<meta property="og:site_name" content="寒秋の博客">
<meta property="og:description" content="0、什么是高阶函数高阶函数英文叫Higher-order function。JavaScript的函数其实都指向某个变量。既然变量可以指向函数，函数的参数能接收变量，那么一个函数就可以接收另一个函数作为参数，这种函数就称之为高阶函数。 1、filter函数的使用（过滤数组） MDN：filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。   filter中的回调函数有一">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/huqian025/my-images/raw/master/js/js%E6%95%B0%E7%BB%84%E4%B8%AD%E7%9A%84%E9%AB%98%E9%98%B6%E5%87%BD%E6%95%B0/foreach%E7%AC%AC%E4%BA%8C%E4%B8%AA%E5%8F%82%E6%95%B0.png">
<meta property="article:published_time" content="2022-01-06T03:34:41.000Z">
<meta property="article:modified_time" content="2022-01-06T03:35:30.636Z">
<meta property="article:author" content="Han Qiu">
<meta property="article:tag" content="js">
<meta property="article:tag" content="数组">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://gitee.com/huqian025/my-images/raw/master/js/js%E6%95%B0%E7%BB%84%E4%B8%AD%E7%9A%84%E9%AB%98%E9%98%B6%E5%87%BD%E6%95%B0/foreach%E7%AC%AC%E4%BA%8C%E4%B8%AA%E5%8F%82%E6%95%B0.png">
  
  
  <title>js数组中的高阶函数 - 寒秋の博客</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 6.0.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>blogs</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="js数组中的高阶函数">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2022-01-06 11:34" pubdate>
        2022年1月6日 中午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      3.7k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      31 分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">js数组中的高阶函数</h1>
            
            <div class="markdown-body">
              <h4 id="0、什么是高阶函数"><a href="#0、什么是高阶函数" class="headerlink" title="0、什么是高阶函数"></a>0、什么是高阶函数</h4><p>高阶函数英文叫Higher-order function。JavaScript的函数其实都指向某个变量。既然变量可以指向函数，函数的参数能接收变量，那么一个函数就可以接收另一个函数作为参数，这种函数就称之为高阶函数。</p>
<h4 id="1、filter函数的使用（过滤数组）"><a href="#1、filter函数的使用（过滤数组）" class="headerlink" title="1、filter函数的使用（过滤数组）"></a>1、filter函数的使用（过滤数组）</h4><blockquote>
<p>MDN：filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。 </p>
</blockquote>
<p>filter中的回调函数有一个要求：必须返回一个boolean值<br>true：当返回为true时，函数内部自动将这次回调的n加入到新的数组中<br>false：当返回为false时，函数内部会过滤掉这次的n</p>
<ul>
<li><p>示例：获取集合中小于100的数</p>
<figure class="highlight js"><table><tr><td class="gutter"><div class="code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></div></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> nums = [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>, <span class="hljs-number">111</span>, <span class="hljs-number">222</span>, <span class="hljs-number">333</span>]<br><span class="hljs-keyword">let</span> newNums = nums.filter(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">n</span>)</span>&#123;<br>    <span class="hljs-keyword">return</span> n&lt;<span class="hljs-number">100</span><br>&#125;)<br></code></pre></td></tr></table></figure></li>
<li><p>示例：js中获取素数</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">get_primes</span>(<span class="hljs-params">arr</span>) </span>&#123;<br>    <span class="hljs-keyword">return</span> arr.filter(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> &#123;<br>        <span class="hljs-comment">// 1不是素数</span><br>        <span class="hljs-keyword">if</span>(num === <span class="hljs-number">1</span>) &#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;<br>        &#125;<br>        <span class="hljs-comment">// 从2开始，取到该数的平方根即可</span><br>        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">var</span> i=<span class="hljs-number">2</span>; i&lt;=<span class="hljs-built_in">Math</span>.sqrt(num); i++) &#123;<br>            <span class="hljs-comment">// 如果可以整除，证明不是素数</span><br>            <span class="hljs-keyword">if</span>(num % i === <span class="hljs-number">0</span>) &#123;<br>                <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;<br>            &#125;<br>        &#125;<br>        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;<br>    &#125;);<br>&#125;<br></code></pre></td></tr></table></figure></li>
</ul>
<h4 id="2、map函数的使用（对数组每个元素进行操作）"><a href="#2、map函数的使用（对数组每个元素进行操作）" class="headerlink" title="2、map函数的使用（对数组每个元素进行操作）"></a>2、map函数的使用（对数组每个元素进行操作）</h4><blockquote>
<p>MDN：map()方法创建一个新数组，其结果是该数组中的每个元素是调用一次提供的函数后的返回值。</p>
</blockquote>
<ul>
<li>示例：将新集合中的所有数*2<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> new2Nums = newNums.map(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">n</span>)</span>&#123;<br>    <span class="hljs-keyword">return</span> n*<span class="hljs-number">2</span><br>&#125;)<br></code></pre></td></tr></table></figure></li>
</ul>
<h4 id="3、reduce函数的使用（汇总数组的内容）"><a href="#3、reduce函数的使用（汇总数组的内容）" class="headerlink" title="3、reduce函数的使用（汇总数组的内容）"></a>3、reduce函数的使用（汇总数组的内容）</h4><blockquote>
<p>MDN：reduce()方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行)，将其结果汇总为单个返回值。</p>
</blockquote>
<ul>
<li>示例：计算集合所有数据的和<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// new2Nums数组的和，preValue为上一次function的返回值，0为preValue初始值</span><br>new2Nums.reduce(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">preValue, n</span>)</span>&#123;<br>    <span class="hljs-keyword">return</span> preValue + n<br>&#125;, <span class="hljs-number">0</span>)<br><br><span class="hljs-comment">// 简化</span><br><span class="hljs-keyword">let</span> total = nums.filter(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">n</span>)</span>&#123;<br>    <span class="hljs-keyword">return</span> n&lt;<span class="hljs-number">100</span><br>&#125;).map(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">n</span>)</span>&#123;<br>    <span class="hljs-keyword">return</span> n*<span class="hljs-number">2</span><br>&#125;).reduce(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">preValue, n</span>)</span>&#123;<br>    <span class="hljs-keyword">return</span> preValue + n<br>&#125;, <span class="hljs-number">0</span>)<br><br><span class="hljs-comment">// 进一步简化：</span><br><span class="hljs-keyword">let</span> total = nums.filter(<span class="hljs-function"><span class="hljs-params">n</span> =&gt;</span> n&lt;<span class="hljs-number">100</span>).map(<span class="hljs-function"><span class="hljs-params">n</span> =&gt;</span> n*<span class="hljs-number">2</span>).reduce(<span class="hljs-function">(<span class="hljs-params">preValue, n</span>) =&gt;</span> preValue +n)<br></code></pre></td></tr></table></figure></li>
</ul>
<h4 id="4、sort函数的使用（数组排序）"><a href="#4、sort函数的使用（数组排序）" class="headerlink" title="4、sort函数的使用（数组排序）"></a>4、sort函数的使用（数组排序）</h4><blockquote>
<p>MDN：sort()方法用<a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/In-place_algorithm">原地算法</a>对数组的元素进行排序，并返回数组。默认排序顺序是在将元素转换为字符串，然后比较它们的UTF-16代码单元值序列时构建的。<a target="_blank" rel="noopener" href="https://juejin.cn/post/6844904159314116622">深入理解字符编码</a></p>
</blockquote>
<p>对于两个元素x和y，如果认为x &lt; y，则返回-1，如果认为x == y，则返回0，如果认为x &gt; y，则返回1。<strong>sort()方法会直接对Array进行修改，它返回的结果仍是当前Array。</strong></p>
<ul>
<li><p>示例：使用sort默认排序</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs js">[<span class="hljs-string">&#x27;Google&#x27;</span>, <span class="hljs-string">&#x27;Apple&#x27;</span>, <span class="hljs-string">&#x27;Microsoft&#x27;</span>].sort(); <span class="hljs-comment">// [&#x27;Apple&#x27;, &#x27;Google&#x27;, &#x27;Microsoft&#x27;];</span><br><br>[<span class="hljs-string">&#x27;Google&#x27;</span>, <span class="hljs-string">&#x27;apple&#x27;</span>, <span class="hljs-string">&#x27;Microsoft&#x27;</span>].sort(); <span class="hljs-comment">// [&#x27;Google&#x27;, &#x27;Microsoft&quot;, &#x27;apple&#x27;]</span><br><br><span class="hljs-comment">//  Array的sort()方法默认把所有元素先转换为String再排序</span><br>[<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>].sort(); <span class="hljs-comment">// [1, 10, 2, 20]</span><br></code></pre></td></tr></table></figure></li>
<li><p>示例：将数组从小到大排序 [10, 20, 1, 2]</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">var</span> arr = [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>];<br><span class="hljs-comment">// 正数相当于1，负数相当于-1</span><br>arr.sort(<span class="hljs-function">(<span class="hljs-params">x, y</span>) =&gt;</span> x-y); <span class="hljs-comment">// [1, 2, 10, 20]</span><br></code></pre></td></tr></table></figure></li>
</ul>
<h4 id="5、every函数的使用（判断数组的所有元素是否满足测试条件）"><a href="#5、every函数的使用（判断数组的所有元素是否满足测试条件）" class="headerlink" title="5、every函数的使用（判断数组的所有元素是否满足测试条件）"></a>5、every函数的使用（判断数组的所有元素是否满足测试条件）</h4><blockquote>
<p>MDN：every()方法测试一个数组内的所有元素是否都能通过某个指定函数的测试。它返回一个布尔值。</p>
</blockquote>
<p><strong>若收到一个空数组，此方法在一切情况下都会返回 true。</strong></p>
<ul>
<li>示例：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">var</span> arr = [<span class="hljs-string">&#x27;Apple&#x27;</span>, <span class="hljs-string">&#x27;pear&#x27;</span>, <span class="hljs-string">&#x27;orange&#x27;</span>];<br><span class="hljs-built_in">console</span>.log(arr.every(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">s</span>) </span>&#123;<br>    <span class="hljs-keyword">return</span> s.length &gt; <span class="hljs-number">0</span>;<br>&#125;)); <span class="hljs-comment">// true, 因为每个元素都满足s.length&gt;0</span><br><br><span class="hljs-built_in">console</span>.log(arr.every(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">s</span>) </span>&#123;<br>    <span class="hljs-keyword">return</span> s.toLowerCase() === s;<br>&#125;)); <span class="hljs-comment">// false, 因为不是每个元素都全部是小写</span><br></code></pre></td></tr></table></figure></li>
</ul>
<h4 id="6、find函数的使用（查找符合条件的第一个元素，返回值）"><a href="#6、find函数的使用（查找符合条件的第一个元素，返回值）" class="headerlink" title="6、find函数的使用（查找符合条件的第一个元素，返回值）"></a>6、find函数的使用（查找符合条件的第一个元素，返回值）</h4><blockquote>
<p>MDN： find()方法返回数组中满足提供的测试函数的第一个元素的值。否则返回undefined。</p>
</blockquote>
<ul>
<li>示例：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">var</span> arr = [<span class="hljs-string">&#x27;Apple&#x27;</span>, <span class="hljs-string">&#x27;pear&#x27;</span>, <span class="hljs-string">&#x27;orange&#x27;</span>];<br><span class="hljs-built_in">console</span>.log(arr.find(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">s</span>) </span>&#123;<br>    <span class="hljs-keyword">return</span> s.toLowerCase() === s;<br>&#125;)); <span class="hljs-comment">// &#x27;pear&#x27;, 因为pear全部是小写</span><br><br><span class="hljs-built_in">console</span>.log(arr.find(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">s</span>) </span>&#123;<br>    <span class="hljs-keyword">return</span> s.toUpperCase() === s;<br>&#125;)); <span class="hljs-comment">// undefined, 因为没有全部是大写的元素</span><br></code></pre></td></tr></table></figure></li>
</ul>
<h4 id="7、findIndex函数的使用（查找符合条件的第一个元素，返回索引）"><a href="#7、findIndex函数的使用（查找符合条件的第一个元素，返回索引）" class="headerlink" title="7、findIndex函数的使用（查找符合条件的第一个元素，返回索引）"></a>7、findIndex函数的使用（查找符合条件的第一个元素，返回索引）</h4><blockquote>
<p>MDN：findIndex()方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回-1。</p>
</blockquote>
<ul>
<li>示例：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">var</span> arr = [<span class="hljs-string">&#x27;Apple&#x27;</span>, <span class="hljs-string">&#x27;pear&#x27;</span>, <span class="hljs-string">&#x27;orange&#x27;</span>];<br><span class="hljs-built_in">console</span>.log(arr.findIndex(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">s</span>) </span>&#123;<br>    <span class="hljs-keyword">return</span> s.toLowerCase() === s;<br>&#125;)); <span class="hljs-comment">// 1, 因为&#x27;pear&#x27;的索引是1</span><br><br><span class="hljs-built_in">console</span>.log(arr.findIndex(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">s</span>) </span>&#123;<br>    <span class="hljs-keyword">return</span> s.toUpperCase() === s;<br>&#125;)); <span class="hljs-comment">// -1</span><br></code></pre></td></tr></table></figure></li>
</ul>
<p><strong>findIndex与indexOf的区别</strong></p>
<ul>
<li>findindex丢进去的是一个函数，找满足函数关系的元素。</li>
<li>indexof丢进去的是要找的元素，直接找元素。</li>
</ul>
<h4 id="8、forEach函数的使用（对数组每个元素进行操作，没有返回值）"><a href="#8、forEach函数的使用（对数组每个元素进行操作，没有返回值）" class="headerlink" title="8、forEach函数的使用（对数组每个元素进行操作，没有返回值）"></a>8、forEach函数的使用（对数组每个元素进行操作，没有返回值）</h4><blockquote>
<p>MDN：forEach()方法对数组的每个元素执行一次给定的函数。</p>
</blockquote>
<p>forEach()和map()类似，它也把每个元素依次作用于传入的函数，但不会返回新的数组。forEach()常用于遍历数组，因此，传入的函数不需要返回值。</p>
<ul>
<li>示例：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">var</span> arr = [<span class="hljs-string">&#x27;Apple&#x27;</span>, <span class="hljs-string">&#x27;pear&#x27;</span>, <span class="hljs-string">&#x27;orange&#x27;</span>];<br>arr.forEach(<span class="hljs-built_in">console</span>.log); <span class="hljs-comment">// 依次打印每个元素</span><br></code></pre></td></tr></table></figure></li>
</ul>
<p>forEach方法可以接收两个参数array.forEach(function(currentValue, index, arr), thisValue)：</p>
<ol>
<li>回调函数，必需，回调函数中有三个参数<ol>
<li>currentValue，必需，当前元素</li>
<li>index，可选，当前元素的索引值</li>
<li>arr，可选，当前元素所属的数组对象</li>
</ol>
</li>
<li>thisValue，可选，传递给参数的值一般用“this”值，如果这个参数为空，“undefined”会传递给“this”值简单点来说，就是我们可以直接使用第二个参数来指定函数里的this的值，而不需要使用箭头函数或者在外面定义var that = this;等操作。 在加上第二个参数前，forEach函数里的this默认是指向window的，在加了第二个参数this之后则指向forEach函数所在的对象了。<br><img src="https://gitee.com/huqian025/my-images/raw/master/js/js%E6%95%B0%E7%BB%84%E4%B8%AD%E7%9A%84%E9%AB%98%E9%98%B6%E5%87%BD%E6%95%B0/foreach%E7%AC%AC%E4%BA%8C%E4%B8%AA%E5%8F%82%E6%95%B0.png" srcset="/img/loading.gif" lazyload alt="forEach方法第二个参数thisValue"></li>
</ol>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/js/">js</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/js/">js</a>
                    
                      <a class="hover-with-bg" href="/tags/%E6%95%B0%E7%BB%84/">数组</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/01/06/js%E6%A0%87%E8%AF%86%E7%AC%A6%E3%80%81%E5%85%B3%E9%94%AE%E5%AD%97%E3%80%81%E4%BF%9D%E7%95%99%E5%AD%97/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">js标识符、关键字、保留字</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/01/06/js%E6%A8%A1%E5%9D%97%E5%8C%96%E8%A7%84%E8%8C%83/">
                        <span class="hidden-mobile">js模块化规范</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
